<script setup>
import { ElMessage } from 'element-plus';
import Layer from "@/components/layer/index.vue";
import { defineProps, ref, defineEmits, reactive } from 'vue'
import { addAPI, updateAPI } from '@/api/wedding/productInfo'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { MessagePlugin, DialogPlugin, Loading } from 'tdesign-vue-next';
import { upload, uploadAttach, delAPI } from '@/api/wedding/attachInfo'

// 使用defineEmits来接收来自父组件的方法
const emit = defineEmits(['getTableData'])
// 声明props
const props = defineProps({
  layer: {
    type: Object,
    default: () => {
      return {
        show: false,
        title: '',
        showButton: true
      }
    }
  }
});

/************************************定义变量************************************************/
const loading = ref(false);
const ruleForm = ref(null)
const layerDom = ref(null)
const rules = {
  categoryId: [{ required: true, message: '请输入商品类别id', trigger: 'blur' }],
  proName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  proAmount: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  proDetails: [{ required: true, message: '请输入商品详情', trigger: 'blur' }],
  selfPickup: [{ required: true, message: '请输入自提点', trigger: 'blur' }],
  inventory: [{ required: true, message: '请输入库存', trigger: 'blur' }],
}
let form = ref({
  id: null,
  userId: null,
  categoryId: null,
  categoryName: null,
  proName: null,
  proAmount: null,
  proDetails: null,
  selfPickup: null,
  inventory: null,
  createTime: null,
  updateTime: null,
  delFlag: null,
  imgUrl: null,
  file: null, // 用于存储上传的文件
  attachIds: [] // 用于存储上传的附件id
})
/************************************上传图片************************************************/
const files1 = ref([]);
const beforeUpload1 = (file) => {
  if (file.size > 5 * 1024 * 1024) {
    MessagePlugin.warning('上传的图片不能大于5M');
    return false;
  }
  return true;
};
const requestMethod1 = async (file) => {
  loading.value = true;
  console.log('[ file ] >', file)
  form.file = file.raw;
  try {
    const res = await upload(form);
    if (res.code === 0) {
      form.value.imgUrl = res.data;
      console.log('[ formqqqqqqqqqqqqqqq ] >', form)
      MessagePlugin.success('上传成功');
      loading.value = false;
      return new Promise((resolve) => {
        resolve({ status: 'success', response: { url: form.imgUrl } });
      });
    }
    MessagePlugin.success(`上传失败:${res.msg}`);
    return new Promise((resolve) => {
      resolve({ status: 'fail', error: '上传失败' });
    });
  } catch (er) {
    MessagePlugin.success(`上传失败:${er}`);
    return new Promise((resolve) => {
      // resolve 参数为关键代码
      resolve({ status: 'fail', error: '上传失败' });
    });
  }
};

/************************************上传轮播图************************************************/
const autoUpload = ref(false);
const showImageFileName = ref(true);
const showUploadButton = ref(true);
const files = ref([]);
const beforeUpload = (file) => {
  if (file.size > 5 * 1024 * 1024) {
    MessagePlugin.warning('上传的图片不能大于5M');
    return false;
  }
  return true;
};
const requestMethod = (res) => new Promise((resolve) => {
  loading.value = true;
  console.log('[ res.raw ] >', res[0].raw);
  let file = res[0];
  try {
    upload({ "file": file.raw }).then(res => {
      if (res.code === 0) {
        const formFile = {
          file: {},
          attachName: null,
          fileType: null,
          fileSize: null,
          sort: null,
          imgUrl: null
        };
        formFile.attachName = file.raw.name;
        formFile.fileType = file.raw.type;
        formFile.fileSize = file.raw.size;
        formFile.filePath = res.data;
        formFile.sort = "1";
        uploadAttach(formFile).then(res1 => {
          if (res1.code == 0) {
            MessagePlugin.success('上传成功');
            if (!Array.isArray(form.value.attachIds)) {
              form.value.attachIds = [];
            }
            form.value.attachIds.push(res1.data.id);
            loading.value = false;
          }
        }).catch(er => {
          MessagePlugin.error(`上传失败:${er}`);
          return new Promise((resolve) => {
            resolve({ status: 'fail', error: '上传失败' });
          });
        });
      }
    }).catch(res => {
      MessagePlugin.success(`上传失败:${res.msg}`);
      return new Promise((resolve) => {
        resolve({ status: 'fail', error: '上传失败' });
      });
    });
  } catch (er) {
    MessagePlugin.success(`上传失败:${er}`);
    return new Promise((resolve) => {
      // resolve 参数为关键代码
      resolve({ status: 'fail', error: '上传失败' });
    });
  }
  resolve({ status: 'success' });
});
const onRemove = (res) => {
  if (!res.file || !res.file.id) {
    return;
  }
  delAPI([res.file.id])
    .then(res => {
      if (res.code === 0) {
        MessagePlugin.success('删除成功');
        // 从form中移除对应的attachId
        if (Array.isArray(form.value.attachIds) && form.value.attachIds.length > 0) {
          const index = form.value.attachIds.indexOf(res.file.id);
          if (index > -1) {
            form.value.attachIds.splice(index, 1);
          }
        }
      } else {
        MessagePlugin.error('删除失败');
      }
    })
    .catch(err => {
      MessagePlugin.error(`删除失败:${err}`);
    });
};
/************************************数据回显************************************************/
if (props.layer.row) {
  if (props.layer.row) {
    let source = props.layer.row
    Object.keys(form.value).forEach(k => k in source && (form.value[k] = source[k]));
    files.value = source.attachInfos || ref([]);
    console.log('[ source.attachInfos ] >', source.attachInfos)
    console.log('[ attachInfos ] >', files)
  }
}

/************************************定义事件************************************************/
//提交按钮事件
let submit = () => {
  if (ruleForm) {
    ruleForm.value.validate((valid) => {
      if (valid) {
        let params = form.value
        if (props.layer.row) {
          updateForm(params)
        } else {
          addForm(params)
        }
      } else {
        return false;
      }
    });
  }
}

let updateForm = (params) => {
  updateAPI(params)
    .then(res => {
      ElMessage({
        type: 'success',
        message: '编辑成功'
      })
      emit('getTableData', false)
      layerDom && layerDom.value.close()
    })
}

let addForm = (params) => {
  console.log('[ params ] >', params)
  addAPI(params)
    .then(res => {
      ElMessage({
        type: 'success',
        message: '新增成功'
      })
      emit('getTableData', true)
      layerDom && layerDom.value.close()
    })
}

/************************************文章富文本处理************************************************/
// 编辑器配置
const editorOptions = {
  debug: 'info',
  modules: {
    toolbar: [
      [{ size: [false, "small", "large", "huge"] }],            // 字号
      [{ header: [false, 1, 2, 3, 4, 5, 6] }],                  // 标题
      [{ color: [] }, { background: [] }],                      // 字体颜色、文本突出显示颜色
      ["bold", "italic", "underline", "strike"],                // 加粗、倾斜、下划线、删除线
      ["blockquote"],                                           // 块引用
      [{ script: "sub" }, { script: "super" }],                 // 下标、上标
      [{ list: "ordered" }, { list: "bullet" }],                // 有序、无序列表
      [{ indent: "-1" }, { indent: "+1" }],                     // 减少缩进量、增加缩进量
      [{ align: [] }],                                          // 对齐、左对齐、居中、右对齐、两端对齐
      ["link", "image", "video"],                       // 链接、图片、视频
      ["clean"],                                                // 清除样式
    ]
  },
  placeholder: '请输入内容~'
}
</script>

<template>
  <Layer :layer="layer" @confirm="submit" ref="layerDom">
    <t-loading size="small" :loading="loading" showOverlay>
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="130px" style="margin-right:30px;">
        <el-form-item label="商品类别：" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择商品类别">
            <el-option v-for="item in props.layer.categoryList" :key="item.id" :label="item.category" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称：" prop="proName">
          <el-input v-model="form.proName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品价格：" prop="proAmount">
          <el-input-number size="large" v-model="form.proAmount" :precision="2" :step="0.1">
            <template #suffix><span>元</span></template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="商品划线价：" prop="oldAmount">
          <el-input-number size="large" v-model="form.oldAmount" :precision="2" :step="0.1">
            <template #suffix><span>元</span></template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="联系方式：" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="自提点：" prop="selfPickup">
          <el-input v-model="form.selfPickup" placeholder="请输入自提点"></el-input>
        </el-form-item>
        <el-form-item label="库存：" prop="inventory">
          <el-input-number size="large" v-model="form.inventory" :precision="0" :step="1">
          </el-input-number>
        </el-form-item>
        <el-form-item label="上传商品主图：" prop="fileName">
          <t-image v-if="form.imgUrl" :src="form.imgUrl" mode="aspectFill" width="72" height="72" aria-label="图片" />
          <t-upload v-model="files1" :tips="'上传文件大小在 5M 以内'" theme="custom" :before-upload="beforeUpload1"
            :request-method="requestMethod1" @remove="onRemove">
            <t-button theme="default" variant="outline" :style="{ marginTop: '10px' }">
              <template #icon> <t-icon name="photo"></t-icon> </template>上传图片</t-button>
          </t-upload>
        </el-form-item>
        <el-form-item label="上传商品轮播图：" prop="fileName">
          <t-upload v-model="files" placeholder="支持批量上传图片文件" theme="image-flow" accept="image/*" multiple
            :request-method="requestMethod" :before-upload="beforeUpload" :auto-upload="autoUpload" :max="8"
            :abridge-name="[6, 6]" :show-image-file-name="showImageFileName"
            :upload-button="showUploadButton ? {} : null"
            :cancel-upload-button="showUploadButton ? { content: '取消上传' } : null" @remove="onRemove"></t-upload>
        </el-form-item>
        <el-form-item label="商品详情：" prop="proDetails">
          <!-- <Editor v-model:model-value="form.modelValue" contentType="html"/> -->
          <!-- <ArticleEditor :initial-data="initialArticle" :loading="isSaving" @save="handleSave" @cancel="handleCancel" /> -->
          <div class="editor-container">
            <QuillEditor v-model:content="form.proDetails" contentType="html" theme="snow" :options="editorOptions" />
          </div>
          <!-- <el-input v-model="form.proDetails" placeholder="请输入商品详情"></el-input> -->
        </el-form-item>
      </el-form>
    </t-loading>
  </Layer>
</template>

<style scoped lang="scss">
.el-input-number--large {
  line-height: 38px;
  width: 230px;
}
</style>

<style lang="scss" scoped>
.editor-container {
  height: 600px;
  width: 120%;
  margin-bottom: 60px;
}

.editor-container {
  ::v-deep {
    .ql-editor {
      min-height: 600px;
      max-height: 1000px;
    }

    .ql-snow.ql-toolbar {
      .ql-picker.ql-header {
        width: 70px;

        .ql-picker-label::before,
        .ql-picker-item::before {
          content: '普通';
        }

        .ql-picker-label[data-value='1']::before,
        .ql-picker-item[data-value='1']::before {
          content: '标题一';
        }

        .ql-picker-label[data-value='2']::before,
        .ql-picker-item[data-value='2']::before {
          content: '标题二';
        }

        .ql-picker-label[data-value='3']::before,
        .ql-picker-item[data-value='3']::before {
          content: '标题三';
        }

        .ql-picker-label[data-value='4']::before,
        .ql-picker-item[data-value='4']::before {
          content: '标题四';
        }

        .ql-picker-label[data-value='5']::before,
        .ql-picker-item[data-value='5']::before {
          content: '标题五';
        }

        .ql-picker-label[data-value='6']::before,
        .ql-picker-item[data-value='6']::before {
          content: '标题六';
        }
      }

      .ql-picker.ql-size {
        width: 70px;

        .ql-picker-label::before,
        .ql-picker-item::before {
          content: '普通';
        }

        .ql-picker-label[data-value='small']::before,
        .ql-picker-item[data-value='small']::before {
          content: '小';
        }

        .ql-picker-label[data-value='large']::before,
        .ql-picker-item[data-value='large']::before {
          content: '中';
        }

        .ql-picker-label[data-value='huge']::before,
        .ql-picker-item[data-value='huge']::before {
          content: '大';
        }
      }
    }

    .ql-snow .ql-tooltip::before {
      content: '链接';
    }

    .ql-snow .ql-tooltip a.ql-action::after {
      content: '编辑';
    }

    .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
      content: '保存';
    }

    .ql-snow .ql-tooltip a.ql-remove::before {
      content: '移除';
    }
  }
}
</style>
